<template>
  <div class="account-report">
    <!-- 标题与操作区 -->
    <div class="header">
      <div class="title">
        <h3>结算账户</h3>
      </div>

      <div class="action-buttons">
        <el-button type="primary" @click="openAddDialog">新增</el-button>
        <el-button @click="batchDisable">禁用</el-button>
        <el-button @click="batchEnable">启用</el-button>
        <el-button @click="refreshTable">刷新</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData.length > 0 ? tableData : emptyTableData"
      border
      style="width: 100%"
      :row-class-name="rowClassName"
      :header-cell-style="headerCellStyle"
      @selection-change="handleSelectionChange"
      ref="accountTable"
    >
      <!-- 复选框列 -->
      <el-table-column type="selection" width="40" />

      <!-- 操作列 -->
      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <div class="table-actions">
            <el-button type="text" class="edit-btn" @click="openEditDialog(row)"
              >修改</el-button
            >
            <el-button type="text" class="delete-btn" @click="handleDelete(row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>

      <!-- 账户编号 -->
      <el-table-column prop="accountNo" label="账户编号" />

      <!-- 账户名称 -->
      <el-table-column prop="accountName" label="账户名称" />

      <!-- 当前余额 -->
      <el-table-column
        prop="currentBalance"
        label="当前余额"
        width="120"
        align="right"
      >
        <template #default="{ row }">
          <span :class="row.currentBalance < 0 ? 'negative-amount' : ''">
            {{ formatAmount(row.currentBalance) }}
          </span>
        </template>
      </el-table-column>

      <!-- 期初余额 -->
      <el-table-column
        prop="initialBalance"
        label="期初余额"
        width="120"
        align="right"
      >
        <template #default="{ row }">
          {{ formatAmount(row.initialBalance) }}
        </template>
      </el-table-column>

      <!-- 建账日期 -->
      <el-table-column prop="setupDate" label="建账日期" width="120" />

      <!-- 账户类别 -->
      <el-table-column prop="accountType" label="账户类别" width="120" />

      <!-- 状态 -->
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-switch v-model="row.status" @change="handleStatusChange(row)" />
        </template>
      </el-table-column>

      <!-- 默认账户标记 -->
      <el-table-column
        prop="isDefault"
        label="默认账户"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <div class="cell-content">
            <span v-if="row.isDefault" class="default-tag">默认账户</span>
            <el-button
              v-else
              type="primary"
              @click="setDefault(row)"
            >
              设置默认
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除确认" width="30%">
      <span>确定要删除账户 "{{ currentAccount?.accountName }}" 吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <AccountDialog
      v-model:visible="editDialogVisible"
      :account-data="currentAccount"
      :title="dialogTitle"
      :is-add-mode="isAddMode"
      @submit="handleSubmit"
      @cancel="handleCancel"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
// import { CirclePlus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import AccountDialog from "@/util/AccountDialog.vue";
import axios from "axios";

// 格式化金额显示
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return "0.00";
  return Number(amount).toFixed(2);
};

// 响应式变量
const deleteDialogVisible = ref(false);
const selectedRows = ref([]);
const accountTable = ref();
const editDialogVisible = ref(false);
const currentAccount = ref({});
const isAddMode = ref(false);
const dialogTitle = ref("");
const tableData = ref([]);


// 加载账户数据
const loadAccountData = async () => {
  try {
    const response = await axios.get('/finance/allAccount');
    console.log('sdfsdsd',response.data)
    if (response.data.code===5200) {
      tableData.value = response.data.allAccount.map(item => ({
        accountNo: item.account_code,
        accountName: item.account_name,
        currentBalance: item.current_balance,
        initialBalance: item.opening_balance,
        setupDate: item.account_creation_date ? new Date(item.account_creation_date).toISOString().split('T')[0] : '',
        accountType: item.account_type,
        status: item.account_enabled === 1,
        isDefault: item.account_isDefault === 1,
        account_id: item.account_id,
        company_code: item.company_code
      }));
    } else {
      ElMessage.error('获取账户数据失败');
    }
  } catch (error) {
    console.error('加载账户数据出错:', error);
    ElMessage.error('加载数据失败，请重试');
  }
};

// 初始化时加载数据
onMounted(() => {
  loadAccountData();
});

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 刷新表格
const refreshTable = () => {
  loadAccountData();
  ElMessage.success("数据已刷新");
};

// 批量禁用
const batchDisable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }
  console.log('sdfsfs',selectedRows.value)
  ElMessageBox.confirm("确定要禁用选中的账户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 批量更新状态
        for (const row of selectedRows.value) {
          await axios.get('/finance/updateEnable', {
            params:{
              account_id: row.account_id,
              account_enabled: 0
              }
            });
          row.status = false;
        }
        ElMessage.success("禁用成功");
      } catch (error) {
        console.error('批量禁用失败:', error);
        ElMessage.error('操作失败，请重试');
        loadAccountData();
      }
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

// 批量启用
const batchEnable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  ElMessageBox.confirm("确定要启用选中的账户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 批量更新状态
        for (const row of selectedRows.value) {
          await axios.get('/finance/updateEnable', {
            params:{
              account_id: row.account_id,
              account_enabled: 1
              }
            });
          row.status = true;
        }
        ElMessage.success("启用成功");
      } catch (error) {
        console.error('批量启用失败:', error);
        ElMessage.error('操作失败，请重试');
        loadAccountData();
      }
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

// 状态改变处理
const handleStatusChange = async (row) => {
  try {
    const newStatus = row.status ? 1 : 0;
    console.log('newsStatus',newStatus)
    const res = await axios.get('/finance/updateEnable', {
      params:{
        account_id: row.account_id,
        account_enabled: newStatus
        }
      });
      console.log('dsd',res.data)
    if(res.data.code===5200){
      const action = row.status ? "启用" : "禁用";
      ElMessage.success(`账户 "${row.accountName}" 已${action}`);
    }else {
      row.status = !row.status; // 切换回原来的状态
      ElMessage.error(res.data.msg || "操作失败");
    }

  } catch (error) {
    console.error('更新状态失败:', error);
    ElMessage.error('操作失败，请重试');
    // 失败时回滚状态并重新加载数据
    row.status = !row.status;
    loadAccountData();
  }
};

// 打开编辑对话框
const openEditDialog = (account) => {
  currentAccount.value = { ...account };
  isAddMode.value = false;
  dialogTitle.value = "编辑结算账户";
  editDialogVisible.value = true;
};

// 打开新增对话框
const openAddDialog = () => {
  currentAccount.value = {};
  isAddMode.value = true;
  dialogTitle.value = "新增结算账户";
  editDialogVisible.value = true;
};

// 处理提交
const handleSubmit = async (formData) => {
  try {
    // 获取公司编码（从token中解析，实际项目中需要根据你的认证方式获取）
    // const token = localStorage.getItem('token'); // 假设token存储在localStorage
    // const companyCode = parseCompanyCodeFromToken(token); // 需要实现解析方法
    const companyCode = 'GS0001';
    if (isAddMode.value) {
      // 新增账户
      const newAccount = {
        account_name: formData.accountName,
        account_type: formData.accountType,
        opening_balance: formData.initialBalance,
        account_creation_date: formData.setupDate,
        account_enabled: 1, // 默认为启用状态
        account_isDefault: 1,
        company_code: companyCode,
        current_balance: formData.initialBalance // 新账户当前余额等于期初余额
      };
      
      await axios.post('/finance/insertAccount', newAccount);
      ElMessage.success("新增账户成功");
    } else {
      // 更新账户
      const updatedAccount = {
        account_id: currentAccount.value.account_id,
        account_code: currentAccount.value.accountNo,
        account_name: formData.accountName,
        account_type: formData.accountType,
        opening_balance: formData.initialBalance,
        account_creation_date: formData.setupDate,
        account_enabled: currentAccount.value.status ? 1 : 0,
        account_isDefault: formData.isDefault ? 1 : 0,
        company_code: currentAccount.value.company_code,
        current_balance: currentAccount.value.currentBalance
      };
      
      await axios.post('/finance/updateById', updatedAccount);
      ElMessage.success("修改账户成功");
    }
    // 重新加载数据
    loadAccountData();
    editDialogVisible.value = false;
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error(isAddMode.value ? "新增失败" : "修改失败");
  }
};



// 删除账户
const handleDelete = (row) => {
  currentAccount.value = row;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
    await axios.get('/finance/deleteById', {
      params: {
        account_id: currentAccount.value.account_id
      }
    });
    ElMessage.success(`账户 "${currentAccount.value.accountName}" 已删除`);
    // 重新加载数据
    loadAccountData();
    deleteDialogVisible.value = false;
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请重试');
  }
};

// 设置默认账户
const setDefault = async (row) => {
  if (row.isDefault) return;
  
  ElMessageBox.confirm("确定要将此账户设为默认账户吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 设置当前账户为默认
        const res = await axios.get('/finance/updateDefault', {
            params:{
              account_id: row.account_id
              }
            });
        if(res.data.code===5200){
          ElMessage.success("默认账户设置成功");
        }else{
          ElMessage.error(res.data.msg);
        }
        
        // 重新加载数据
        loadAccountData();
      } catch (error) {
        console.error('设置默认账户失败:', error);
        ElMessage.error('设置失败，请重试');
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};
// 处理取消
const handleCancel = () => {
  editDialogVisible.value = false;
};
// 表头样式
const headerCellStyle = {
  backgroundColor: "#f5f7fa",
  fontWeight: "normal",
  color: "#606266",
};

// 行样式处理
const rowClassName = ({ row }) => {
  return row.isPlaceholder ? "placeholder-row" : "";
};

// 从token解析公司编码（需要根据实际JWT结构实现）
// const parseCompanyCodeFromToken = (token) => {
//   // 实际项目中需要解析JWT获取公司编码
//   // 这里仅为示例
//   return 'DEFAULT_COMPANY';
// };
</script>

<style scoped>
.account-report {
  padding: 15px;
  background-color: #fff;
  min-height: 400px;
}

/* 标题区域 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.account-manage {
  color: #1989fa;
  padding: 0;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 8px;
}

/* 表格样式 */
::v-deep .el-table {
  border: 1px solid #e4e7ed;
}

/* 占位行样式 */
::v-deep .placeholder-row {
  height: 48px;
  opacity: 0.3;
}

/* 操作按钮样式 */
.table-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.edit-btn {
  color: #409eff;
  padding: 0;
}

.delete-btn {
  color: #f56c6c;
  padding: 0;
}

/* 金额样式 */
.negative-amount {
  color: #f56c6c;
}

/* 默认账户标签 */
.default-tag {
  background-color: #ecf5ff;
  color: #409eff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}
.cell-content {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

:deep(.el-table .el-table__row.summary-row) {
  background-color: #f8f8f8 !important;
  font-weight: bold;
}

:deep(.el-table .el-table__row.summary-row:hover > td) {
  background-color: #fff4bf !important;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #fff4bf !important;
}
</style>